package com.kky.pp.activity.index

import android.Manifest
import android.animation.Animator
import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.provider.Settings
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.AccelerateInterpolator
import android.view.animation.Interpolator
import android.view.animation.LinearInterpolator
import android.widget.*
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.app.ActivityCompat
import androidx.core.app.ActivityOptionsCompat
import androidx.core.util.Pair
import androidx.core.view.isVisible
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.SimpleItemAnimator
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.custom.base.config.BaseConfig
import com.custom.base.entity.OkHttpBodyEntity
import com.custom.base.http.OkHttpFromBoy
import com.custom.base.http.OkHttpManager
import com.custom.base.http.SDOkHttpResoutCallBack
import com.custom.base.mvp.MVPBaseFragment
import com.custom.base.util.IntentUtil
import com.custom.base.util.SDHandlerUtil
import com.custom.base.util.ToastUtil
import com.gyf.immersionbar.ImmersionBar
import com.kky.pp.common.Constant
import com.kky.pp.R
import com.kky.pp.adapter.CardStackAdapter
import com.kky.pp.bean.AvatarBean
import com.kky.pp.bean.CardModelBean
import com.kky.pp.bean.TOListBean
import com.kky.pp.popup.CustomPopup
import com.kky.pp.popup.TOListPopup
import com.kky.pp.popup.MemberBuyPopup
import com.kky.pp.entity.CardInfoEntity
import com.kky.pp.entity.MatchResultEntity
import com.kky.pp.entity.MemberSubscribeEntity
import com.kky.pp.entity.ResultDataEntity
import com.kky.pp.pay.GooglePayUtils
import com.kky.pp.activity.wlm.UpSourceEnum
import com.kky.pp.activity.user.UserProfileInfoActivity
import com.kky.pp.activity.fc.FlashChatActivity
import com.kky.pp.util.likeOrDisLikeAnimation
import com.kky.pp.util.likeOrDisLikeClickAnimation
import com.kky.pp.callback.UserProfileCallBackListener
import com.kky.pp.activity.match.MatchedActivity
import com.kky.pp.util.CollectionUtils
import com.kky.pp.util.DateUtils
import com.kky.pp.common.MemberPopupShow.memberBuyShow
import com.kky.pp.util.PermissionUtils
import com.kky.pp.util.SystemUtils
import com.kky.pp.view.video.PrepareView
import com.kky.pp.view.video.StandardVideoController
import com.kky.pp.view.SpotDiffCallback
import com.kky.pp.view.cardstackview.CardStackLayoutManager
import com.kky.pp.view.cardstackview.CardStackListener
import com.kky.pp.view.cardstackview.Direction
import com.kky.pp.view.cardstackview.Duration
import com.kky.pp.view.cardstackview.StackFrom
import com.kky.pp.view.cardstackview.SwipeAnimationSetting
import com.kky.pp.view.cardstackview.SwipeableMethod
import com.custom.base.base.SDBaseEvent
import com.custom.base.base.SDEventManager
import com.kky.pp.util.DensityUtil
import com.youth.banner.Banner
import io.rong.imkit.SpName
import io.rong.imkit.entity.OrderCreateEntity
import io.rong.imkit.event.EnumEventTag
import io.rong.imkit.event.FirebaseEventTag
import com.kky.pp.callback.EmptySuccessCallBack
import com.kky.pp.databinding.FragmentOneBinding
import io.rong.imkit.utils.FirebaseEventUtils
import io.rong.imkit.utils.JsonUtils
import io.rong.imkit.utils.StatusBarUtil
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import org.json.JSONObject
import xyz.doikki.videoplayer.player.BaseVideoView
import xyz.doikki.videoplayer.player.VideoView
import java.util.Date


class IndexFragment : MVPBaseFragment<IndexContract.View, IndexPresenter, FragmentOneBinding>(FragmentOneBinding::inflate),
    IndexContract.View,
    CardStackListener {
    private var isFlashChat: Boolean = false
    private var turnOns: Boolean = true//是否编辑turnOns,默认为true，不展示
    private var newUserFlag: Boolean = true//是否新老客  true 新客  false  老客
    private var turnOnsLimit: Int = 0//turn-ons编辑引导滑动次数
    private var continuousPassNum: Int = 0//连续不喜欢的次数
    private var onlineCmPosition: Int = 0//在线的cm坐标
    private var locationLimit: Int = 5//定位授权连续pass次数
    private var noMatchData: CardInfoEntity.Data? = null
    private val manager by lazy { CardStackLayoutManager(mActivity, this) }

    var userProfileCallBackListener: UserProfileCallBackListener? = null
    private val adapter by lazy {
        CardStackAdapter(
            arrayListOf(),
            this@IndexFragment,
            mActivity,
            turnOns,
            turnOnsLimit,
            newUserFlag,
            continuousPassNum,
            manager
        )
    }

    override fun bindLayout(): Int {
        return R.layout.fragment_one
    }

    override fun initView(view: View) {
        fragmentViewBinding?.conIndexFragMain?.setPadding(
            0,
            StatusBarUtil.getStatusBarHeight(mActivity),
            0,
            0
        )
        (fragmentViewBinding?.txtIndexFragTitle?.layoutParams as ConstraintLayout.LayoutParams).setMargins(
            0,
            0,
            0,
            0
        )
        BaseConfig.getInstance.setInt(SpName.firstChatShow, -1)
        setupCardStackView()
        if (SystemUtils.isConnected(mActivity)) {
            initPaginate()
        } else {
            fragmentViewBinding?.lottieIndexFragLoader?.cancelAnimation()
            fragmentViewBinding?.lottieIndexFragLoader?.visibility = View.GONE
            fragmentViewBinding?.conIndexFragUserList?.visibility = View.GONE
            fragmentViewBinding?.linearIndexFragNoMore?.visibility = View.GONE
            fragmentViewBinding?.linearIndexFragNetworkErrorContainer?.visibility = View.VISIBLE
        }
        initListener()
        fragmentViewBinding?.frameIndexFragLike?.likeOrDisLikeAnimation(
            adapter,
            fragmentViewBinding?.frameIndexFragUnLike!!,
            manager
        )
//        ivGuide.initGuide {
//            if (userActionContainer.isVisible){
//            }else{
//                isViewBubble = true
//            }
//        }
        fragmentViewBinding?.txtIndexFragGoFlirtWithAll?.setOnClickListener {
            SDEventManager.post(EnumEventTag.INDEX_TO_WLM.ordinal)
        }
    }


    fun initListener() {
        fragmentViewBinding?.imgViewIndexFragUnLike?.setOnClickListener {
            fragmentViewBinding?.cardViewIndexFrag
            fragmentViewBinding?.frameIndexFragUnLike?.likeOrDisLikeClickAnimation(
                adapter,
                Direction.Left,
                manager
            )
            dislikeMethod()
        }
        fragmentViewBinding?.imgViewIndexFragLike?.setOnClickListener {
            isFlashChat = false
            fragmentViewBinding?.frameIndexFragLike?.likeOrDisLikeClickAnimation(
                adapter,
                Direction.Right,
                manager
            )
            likeMethod()
        }
        fragmentViewBinding?.countDownIndexFragThirdDaysAgo?.setTimeFinish {
            if (fragmentViewBinding?.conIndexFragThirdDaysAgoContainer != null) {
                fragmentViewBinding?.conIndexFragThirdDaysAgoContainer?.visibility = View.GONE
                fragmentViewBinding?.conIndexFragMain?.setPadding(
                    0,
                    StatusBarUtil.getStatusBarHeight(mActivity),
                    0,
                    0
                )
                (fragmentViewBinding?.txtIndexFragTitle?.layoutParams as ConstraintLayout.LayoutParams).setMargins(
                    0,
                    0,
                    0,
                    0
                )
            }
            initPaginate()
        }
        fragmentViewBinding?.imgViewIndexFragQuickChat?.setOnClickListener {
            val bundle = Bundle()
            if (adapter.getSpots().isEmpty())
                return@setOnClickListener
            bundle.putString("userName", adapter.getSpots()[manager.topPosition].nickName)
            bundle.putString("userCode", adapter.getSpots()[manager.topPosition].friendUserCode)
            bundle.putString("avatar", adapter.getSpots()[manager.topPosition].avatarUrl)
            bundle.putString(UpSourceEnum.SOURCE.name, UpSourceEnum.HOME.name)
            IntentUtil.startActivity(FlashChatActivity::class.java, bundle)
        }
        fragmentViewBinding?.linearIndexFragNetworkErrorTryAgain?.setOnClickListener {
            fragmentViewBinding?.lottieIndexFragNetworkErrorLoading?.visibility = View.VISIBLE
            fragmentViewBinding?.lottieIndexFragNetworkErrorLoading?.playAnimation()
            if (SystemUtils.isConnected(mActivity)) {
                initPaginate()
            } else {
                fragmentViewBinding?.lottieIndexFragNetworkErrorLoading?.visibility = View.GONE
                fragmentViewBinding?.lottieIndexFragNetworkErrorLoading?.pauseAnimation()
                ToastUtil.toast(getString(R.string.ooops_network_error))
            }

        }
        fragmentViewBinding?.txtIndexFragThridDaysAgoUnlockNow?.setOnClickListener {
            FirebaseEventUtils.logEvent(FirebaseEventTag.Home_Unlock_Sub.name)
            MemberBuyPopup(mActivity, 0, object : MemberBuyPopup.ChangeMembershipListener {
                override fun onListener(bean: MemberSubscribeEntity.Data.ProductDescriptions) {
                    OkHttpManager.instance.requestInterface(object : OkHttpFromBoy {
                        override fun addBody(requestBody: OkHttpBodyEntity) {
                            requestBody.setPost(Constant.user_create_order_url)
                            requestBody.add("productCode", bean.productCode)
                            requestBody.add("productCategory", 1)
                        }

                    }, object : SDOkHttpResoutCallBack<OrderCreateEntity>() {
                        override fun onSuccess(entity: OrderCreateEntity) {
                            GooglePayUtils.instance.start(
                                entity,
                                mActivity,
                                object : EmptySuccessCallBack {
                                    override fun OnSuccessListener() {
                                        FirebaseEventUtils.logEvent(FirebaseEventTag.Home_Unlock_Subsuccess.name)
                                        initPaginate()
                                    }

                                })
                        }
                    })
                }

                override fun closeListener(refreshTime: Long) {

                }

            })
        }
        adapter.upUserProfileListener(object : CardStackAdapter.UpUserProfileListener {
            @SuppressLint("CheckResult")
            override fun upUserProfile(
                spot: CardModelBean,
                userBanner: Banner<*, *>
            ) {
                FirebaseEventUtils.logEvent(FirebaseEventTag.Home_Profile.name)
                val bundle = Bundle()
                bundle.putString("userCode", spot.userCode)
                bundle.putString("userCodeFriend", spot.friendUserCode)
                bundle.putBoolean("isIndex", true)
                bundle.putInt("currentItem", userBanner.currentItem)
                fragmentViewBinding?.imgViewIndexFragSeat?.isVisible = true
                val avatarBeanUrl =
                    (userBanner.adapter.getData(userBanner.currentItem) as AvatarBean).imageUrl
                fragmentViewBinding?.imgViewIndexFragSeat?.let {
                    Glide.with(this@IndexFragment)
                        .load(avatarBeanUrl)
                        .into(it)
                }
                Handler().postDelayed({
                    val pair1: Pair<View, String> =
                        Pair.create(
                            fragmentViewBinding?.imgViewIndexFragSeat,
                            fragmentViewBinding?.imgViewIndexFragSeat?.transitionName
                        )
                    val pair2: Pair<View, String> =
                        Pair.create(
                            fragmentViewBinding?.conIndexFragUserActionContainer,
                            fragmentViewBinding?.conIndexFragUserActionContainer?.transitionName
                        )
                    val optionsCompat1: ActivityOptionsCompat =
                        ActivityOptionsCompat.makeSceneTransitionAnimation(mActivity, pair1, pair2)
                    val intent = Intent(mActivity, UserProfileInfoActivity::class.java)
                    intent.putExtra("url", avatarBeanUrl)
                    intent.putExtras(bundle)
                    ActivityCompat.startActivity(mActivity, intent, optionsCompat1.toBundle())
                    userProfileCallBackListener =
                        UserProfileCallBackListener(object : UserProfileCallBackListener.Listener {
                            override fun callBack(currentItem: Int) {
                                userBanner.currentItem = currentItem
                            }
                        })
                }, 100)
            }
        })
        checkWelcomeBack()
    }

    private fun setupCardStackView() {
        initialize()
    }

    private fun startVideo(data: CardInfoEntity.Data) {
        fragmentViewBinding?.txtIndexFragMatchDesc?.text = data.noticeMsg
        val controller = StandardVideoController(mActivity)
        //根据屏幕方向自动进入/退出全屏
        controller.setEnableOrientation(false)
        val prepareView = PrepareView(mActivity) //准备播放界面
        prepareView.setClickStart()
        val thumb = prepareView.findViewById<ImageView>(R.id.imgViewPlayerPrepareThumbView) //封面图
        Glide.with(this)
            .load(data.defaultCoverImage)
            .into(thumb)
        controller.addControlComponent(prepareView)
        controller.setDoubleTapTogglePlayEnabled(false)
        //如果你不想要UI，不要设置控制器即可
        fragmentViewBinding?.videoIndexFrag?.setVideoController(controller)
        val url = data.coverImage
        fragmentViewBinding?.videoIndexFrag?.setUrl(url)
        //播放状态监听
        fragmentViewBinding?.videoIndexFrag?.addOnStateChangeListener(mOnStateChangeListener)
        fragmentViewBinding?.videoIndexFrag?.isMute = true
        fragmentViewBinding?.videoIndexFrag?.setScreenScaleType(VideoView.SCREEN_SCALE_CENTER_CROP)
        fragmentViewBinding?.videoIndexFrag?.start()
    }

    /**
     * 视频监听
     */
    private val mOnStateChangeListener: BaseVideoView.OnStateChangeListener =
        object : BaseVideoView.SimpleOnStateChangeListener() {
            override fun onPlayerStateChanged(playerState: Int) {
                when (playerState) {
                    VideoView.PLAYER_NORMAL -> {
                    }

                    VideoView.PLAYER_FULL_SCREEN -> {
                    }
                }
            }

            override fun onPlayStateChanged(playState: Int) {
                when (playState) {
                    VideoView.STATE_IDLE -> {
                    }

                    VideoView.STATE_PREPARING -> {
                    }

                    VideoView.STATE_PREPARED -> {
                    }

                    VideoView.STATE_PLAYING -> {
                        //需在此时获取视频宽高

                    }

                    VideoView.STATE_PAUSED -> {
                    }

                    VideoView.STATE_BUFFERING -> {
                    }

                    VideoView.STATE_BUFFERED -> {
                    }

                    VideoView.STATE_PLAYBACK_COMPLETED -> {
                        fragmentViewBinding?.videoIndexFrag?.replay(true)
                    }

                    VideoView.STATE_ERROR -> {
                    }
                }
            }
        }

    override fun onResume() {
        super.onResume()
        ImmersionBar.with(mActivity).statusBarDarkFont(false).init()
        if (fragmentViewBinding?.imgViewIndexFragSeat?.isVisible!!) {
            Handler().postDelayed(
                { fragmentViewBinding?.imgViewIndexFragSeat?.isVisible = false },
                300
            )
        }
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden) {
//            ImmersionBar.with(this)
//                .statusBarColor("#96ffffff")
//                .init()
        }
    }


    //实现“onRequestPermissionsResult”函数接收校验权限结果
    override fun onEventMainThread(event: SDBaseEvent) {
        when (EnumEventTag.valueOf(event.tagInt)) {
            EnumEventTag.INDEX_DISLIKE_SWIPED -> {
                Handler().postDelayed({
                    fragmentViewBinding?.frameIndexFragUnLike?.likeOrDisLikeClickAnimation(
                        adapter,
                        Direction.Left,
                        manager
                    )
                    dislikeMethod()
                }, 150)

            }

            EnumEventTag.INDEX_LIKE_SWIPED -> {
                Handler().postDelayed({
                    if (event.data != null) {
                        isFlashChat = event.data.toString().toBoolean()
                    }
                    fragmentViewBinding?.conIndexFragUserActionContainer?.isVisible = true
                    fragmentViewBinding?.frameIndexFragLike?.likeOrDisLikeClickAnimation(
                        adapter,
                        Direction.Right,
                        manager
                    )
                    likeMethod()
                }, 150)
            }

            EnumEventTag.INDEX_REFRESH_DATA -> {
                initPaginate()
            }

            EnumEventTag.INDEX_REFRESH_DATA_ITEM -> {
                if (JsonUtils.isJSON(event.data.toString())) {
                    val jsonObject = JSONObject(event.data.toString())
                    refreshItem(jsonObject.getString("userCode"), jsonObject.getInt("online"))
                }
            }

            EnumEventTag.INDEX_COUNTDOWN_SHOW -> {
                val refreshTime = event.data.toString().toLong()
                fragmentViewBinding?.conIndexFragThirdDaysAgoContainer?.visibility = View.VISIBLE
                fragmentViewBinding?.conIndexFragMain?.setPadding(0, 0, 0, 0)
                (fragmentViewBinding?.txtIndexFragTitle?.layoutParams as ConstraintLayout.LayoutParams).setMargins(
                    0,
                    StatusBarUtil.getStatusBarHeight(mActivity),
                    0,
                    0
                )
                fragmentViewBinding?.conIndexFragUserList?.visibility = View.GONE
//                noMatchData?.let { startVideo(it) }
                fragmentViewBinding?.linearIndexFragNoMore?.visibility = View.GONE
                fragmentViewBinding?.linearIndexFragNetworkErrorContainer?.visibility = View.GONE
                val hours: Long = refreshTime / 60 / 60
                val min = (refreshTime - hours * 60 * 60) / 60
                val s = refreshTime - hours * 60 * 60 - min * 60
                fragmentViewBinding?.countDownIndexFragThirdDaysAgo?.setTime(
                    hours.toInt(),
                    min.toInt(),
                    s.toInt()
                )
                fragmentViewBinding?.countDownIndexFragThirdDaysAgo?.start()
            }

            else -> {}
        }
    }

    /**
     * 喜欢的点击事件
     */
    private fun likeMethod() {
        if (!isFlashChat) {
            if (!BaseConfig.getInstance.getBoolean(SpName.isMember, false)) {
                if (BaseConfig.getInstance.getInt(SpName.remainingWlmNum, 0) <= 0) {
                    memberBuyShow(1, context!!)
                    return
                }
            }
        }
        val direction = Direction.Right
        val duration = Duration.Normal.duration
        val interpolator: Interpolator = AccelerateInterpolator()
        val swipeAnimationSetting = SwipeAnimationSetting.Builder()
            .setDirection(direction)
            .setDuration(duration)
            .setInterpolator(interpolator)
            .build()
        manager.setSwipeAnimationSetting(swipeAnimationSetting)
        fragmentViewBinding?.cardViewIndexFrag?.swipe()
    }

    /**
     * 不喜欢的点击事件
     */
    private fun dislikeMethod() {
        if (!BaseConfig.getInstance.getBoolean(SpName.isMember, false)) {
            if (BaseConfig.getInstance.getInt(SpName.remainingBrowseBNum, 0) <= 0) {
                FirebaseEventUtils.logEvent(FirebaseEventTag.Home_Profile_View_Sub.name)
                memberBuyShow(2, context!!)
                return
            }
        }

        val direction = Direction.Left
        val duration = Duration.Normal.duration
        val interpolator: Interpolator = AccelerateInterpolator()
        val swipeAnimationSetting = SwipeAnimationSetting.Builder()
            .setDirection(direction)
            .setDuration(duration)
            .setInterpolator(interpolator)
            .build()
        manager.setSwipeAnimationSetting(swipeAnimationSetting)
        fragmentViewBinding?.cardViewIndexFrag?.swipe()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == 10009) {
            SDEventManager.post(true, EnumEventTag.INDEX_LIKE_SWIPED.ordinal)
        } else if (requestCode == UserProfileInfoActivity.ACTIVITY_RESULT_CODE) {
            val currentItem = data?.getIntExtra("currentItem", 0)
            currentItem?.let {
                userProfileCallBackListener?.listener?.callBack(
                    it
                )
            }
        }
    }

    //    override val cardStackView: CardStackView
//        get() = card_stack_view
//    override val userDislike: DelayClickImageView
//        get() = user_dislike
//    override val viewUserLike: DelayClickImageView
//        get() = view_user_like
//    override val userChat: DelayClickImageView
//        get() = user_chat
//    override val listLoaderJson: LottieAnimationView
//        get() = list_loader_json
//    override val networkErrorLoading: LottieAnimationView
//        get() = network_error_loading
//    override val containerUserList: ConstraintLayout
//        get() = container_user_list
//    override val networkErrorContainer: LinearLayout
//        get() = network_error_container
//    override val networkErrorTryAgain: LinearLayout
//        get() = network_error_try_again
//    override val threeDaysAgoContainer: ConstraintLayout
//        get() = three_days_ago_container
//    override val threeDaysAgoUnlockNow: TextView
//        get() = three_days_ago_unlock_now
//    override val threeDaysAgoCountDown: SnapUpCountDownTimerView
//        get() = three_days_ago_count_down
//    override val userActionContainer: ConstraintLayout
//        get() = user_action_container
//    override val viewLike: FrameLayout
//        get() = view_like
//    override val viewDisLike: FrameLayout
//        get() = view_dis_like
//    override val listLoaderJsonAvatar: CircleImageView
//        get() = list_loader_json_avatar

    /**
     * 卡片初始化配置
     */
    private fun initialize() {
//        manager.setVisibleCount(3)
        manager.setStackFrom(StackFrom.Top)
        manager.setTranslationInterval(4.0f)
        manager.setScaleInterval(0.9f)
        manager.setSwipeThreshold(0.6f)
        manager.setMaxDegree(50.0f)
        manager.setDirections(Direction.HORIZONTAL)
        manager.setCanScrollHorizontal(true)
        manager.setCanScrollVertical(false)
        manager.setSwipeableMethod(SwipeableMethod.AutomaticAndManual)
        manager.setOverlayInterpolator(LinearInterpolator())
        val direction = Direction.Left
        val duration = Duration.Normal.duration
        val interpolator: Interpolator = AccelerateInterpolator()
        val swipeAnimationSetting = SwipeAnimationSetting.Builder()
            .setDirection(direction)
            .setDuration(duration)
            .setInterpolator(interpolator)
            .build()
        manager.setSwipeAnimationSetting(swipeAnimationSetting)
        fragmentViewBinding?.cardViewIndexFrag?.layoutManager = manager
        fragmentViewBinding?.cardViewIndexFrag?.adapter = adapter
        // 解决调用 notifyItemChanged 闪烁问题,取消默认动画
        (fragmentViewBinding?.cardViewIndexFrag?.itemAnimator as SimpleItemAnimator).supportsChangeAnimations =
            false
        fragmentViewBinding?.cardViewIndexFrag?.itemAnimator.apply {
            if (this is DefaultItemAnimator) {
                supportsChangeAnimations = false
            }
        }
    }

    /**
     * 获取列表数据
     */
    private fun initPaginate() {
        Glide.with(mActivity).load(BaseConfig.getInstance.getString(SpName.avatarUrl, ""))
            .into(fragmentViewBinding?.lottieIndexFragLoaderAvatar!!)
        fragmentViewBinding?.lottieIndexFragLoaderAvatar?.visibility = View.VISIBLE

        OkHttpManager.instance.requestInterface(object : OkHttpFromBoy {
            override fun addBody(requestBody: OkHttpBodyEntity) {
                requestBody.setPost(Constant.match_user_url)
            }
        }, object : SDOkHttpResoutCallBack<CardInfoEntity>() {
            override fun onSuccess(entity: CardInfoEntity) {
                try {
                    noMatchData = entity.data
                    newUserFlag = entity.data.newUserFlag
                    turnOns = entity.data.turnOns
                    turnOnsLimit = entity.data.turnOnsLimit
                    BaseConfig.getInstance.setInt(
                        SpName.remainingBrowseBNum,
                        entity.data.remainingBrowseBNum
                    )
                    BaseConfig.getInstance.setInt(
                        SpName.remainingWlmNum,
                        entity.data.remainingWlmNum
                    )
                    BaseConfig.getInstance.setBoolean(SpName.isMember, entity.data.ismember)
                    if (!CollectionUtils.isEmpty(entity.data.homepageList)) {
                        HomeCardPreloadHelper.preloadPic(mActivity, entity.data.homepageList)
                        var preloadIndex = 0
                        //预加载卡片数量
                        var preloadSize = 6
                        for (i in 0 until entity.data.homepageList.size) {
                            if (entity.data.homepageList[i].online == 1 && entity.data.homepageList[i].userType == 2 && onlineCmPosition <= 2) {
                                onlineCmPosition++
                                BaseConfig.getInstance.setInt(SpName.firstChatShow, i)
                            }
                        }
                    }
                    SDHandlerUtil.runOnUiThreadDelayed(Runnable {
                        if (fragmentViewBinding?.lottieIndexFragLoader != null) {
                            fragmentViewBinding?.lottieIndexFragLoader?.cancelAnimation()
                            fragmentViewBinding?.lottieIndexFragLoader?.visibility = View.GONE
                            fragmentViewBinding?.lottieIndexFragLoaderAvatar?.visibility = View.GONE
                        }
                        if (fragmentViewBinding?.lottieIndexFragNetworkErrorLoading?.isVisible == true) {
                            fragmentViewBinding?.lottieIndexFragNetworkErrorLoading?.visibility =
                                View.GONE
                            fragmentViewBinding?.lottieIndexFragNetworkErrorLoading?.cancelAnimation()
                        }

                        fragmentViewBinding?.linearIndexFragNetworkErrorContainer?.visibility =
                            View.GONE
                        when (entity.data.preferentialFlag) {
                            1 -> {
                                fragmentViewBinding?.conIndexFragThirdDaysAgoContainer?.visibility =
                                    View.VISIBLE
                                fragmentViewBinding?.conIndexFragMain?.setPadding(0, 0, 0, 0)
                                (fragmentViewBinding?.txtIndexFragTitle?.layoutParams as ConstraintLayout.LayoutParams).setMargins(
                                    0,
                                    StatusBarUtil.getStatusBarHeight(mActivity),
                                    0,
                                    0
                                )
                                fragmentViewBinding?.conIndexFragUserList?.visibility = View.GONE
//                                startVideo(entity.data)
                                fragmentViewBinding?.linearIndexFragNoMore?.visibility = View.GONE
                                fragmentViewBinding?.linearIndexFragNetworkErrorContainer?.visibility =
                                    View.GONE
                                val hours: Long = entity.data.refreshTime / 60 / 60
                                val min = (entity.data.refreshTime - hours * 60 * 60) / 60
                                val s = entity.data.refreshTime - hours * 60 * 60 - min * 60
                                fragmentViewBinding?.countDownIndexFragThirdDaysAgo?.setTime(
                                    hours.toInt(),
                                    min.toInt(),
                                    s.toInt()
                                )
                                fragmentViewBinding?.countDownIndexFragThirdDaysAgo?.start()
                            }

                            else -> {
                                fragmentViewBinding?.conIndexFragMain?.setPadding(
                                    0,
                                    StatusBarUtil.getStatusBarHeight(mActivity),
                                    0,
                                    0
                                )
                                (fragmentViewBinding?.txtIndexFragTitle?.layoutParams as ConstraintLayout.LayoutParams).setMargins(
                                    0,
                                    0,
                                    0,
                                    0
                                )
                                fragmentViewBinding?.conIndexFragThirdDaysAgoContainer?.visibility =
                                    View.GONE
                                fragmentViewBinding?.conIndexFragUserList?.visibility =
                                    if (CollectionUtils.isEmpty(entity.data.homepageList)) View.GONE else View.VISIBLE
                                fragmentViewBinding?.linearIndexFragNoMore?.visibility =
                                    if (CollectionUtils.isEmpty(entity.data.homepageList)) View.VISIBLE else View.GONE
                                if (!CollectionUtils.isEmpty(entity.data.homepageList)) {
                                    adapter.setNewUserFlag(newUserFlag)
                                    adapter.setTurnOns(turnOns)
                                    adapter.turnOnsLimit = turnOnsLimit
                                    val old = arrayListOf<CardModelBean>()
                                    val new = old.plus(entity.data.homepageList)
                                    val callback = SpotDiffCallback(old, new)
                                    val result = DiffUtil.calculateDiff(callback)
                                    adapter.setSpots(new)
                                    result.dispatchUpdatesTo(adapter)
                                }
                            }
                        }

                    }, 2200)
                } catch (_: Exception) {

                }
            }

            override fun onFailure(code: Int, msg: String) {
                if (fragmentViewBinding?.lottieIndexFragLoader != null) {
                    fragmentViewBinding?.lottieIndexFragLoader?.cancelAnimation()
                    fragmentViewBinding?.lottieIndexFragLoader?.visibility = View.GONE
                }
                fragmentViewBinding?.conIndexFragUserList?.visibility = View.GONE
                fragmentViewBinding?.linearIndexFragNoMore?.visibility = View.GONE
                fragmentViewBinding?.linearIndexFragNetworkErrorContainer?.visibility = View.VISIBLE
                if (fragmentViewBinding?.lottieIndexFragNetworkErrorLoading?.isVisible == true) {
                    fragmentViewBinding?.lottieIndexFragNetworkErrorLoading?.visibility = View.GONE
                    fragmentViewBinding?.lottieIndexFragNetworkErrorLoading?.cancelAnimation()
                }
            }
        }, isShowDialog = false)
    }

    private fun paginate() {
        OkHttpManager.instance.requestInterface(object : OkHttpFromBoy {
            override fun addBody(requestBody: OkHttpBodyEntity) {
                requestBody.setPost(Constant.match_user_url)
                requestBody.add("recordNum", 10)
            }
        }, object : SDOkHttpResoutCallBack<CardInfoEntity>() {
            override fun onSuccess(entity: CardInfoEntity) {
                try {
                    BaseConfig.getInstance.setBoolean(SpName.isMember, entity.data.ismember)
                    if (CollectionUtils.isNotEmpty(entity.data.homepageList)) {
                        for (i in 0 until entity.data.homepageList.size) {
                            repeat(entity.data.homepageList[i].images.size) {
                                if (CollectionUtils.isNotEmpty(entity.data.homepageList[i].images)) {
                                    Glide.with(mActivity)
                                        .load(entity.data.homepageList[i].images[it].imageUrl)
                                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                                        .preload()
                                }
                            }

                        }
                    }
                    if (CollectionUtils.isNotEmpty(entity.data.homepageList)) {
                        val old = adapter.getSpots()
                        val new = old.plus(entity.data.homepageList)
                        adapter.setSpots(new)
                        adapter.notifyItemRangeChanged(
                            manager.topPosition + 1,
                            new.size - manager.topPosition - 1
                        )
                    }
                } catch (_: Exception) {

                }
            }

            override fun onFailure(code: Int, msg: String) {
            }
        })

    }

    /**
     * 检查是否是注销用户回归
     */
    private fun checkWelcomeBack() {
        OkHttpManager.instance.requestInterface(object : OkHttpFromBoy {
            override fun addBody(requestBody: OkHttpBodyEntity) {
                requestBody.setGet(Constant.check_logout)
                requestBody.add("userCode", BaseConfig.getInstance.getString(SpName.userCode, ""))
            }
        }, object : SDOkHttpResoutCallBack<ResultDataEntity<String>>() {
            override fun onSuccess(entity: ResultDataEntity<String>) {
                entity.data?.let { showWelcomeBackDialog(it) }
            }

            override fun onFailure(code: Int, msg: String) {
            }
        })
    }

    private fun showWelcomeBackDialog(content: String) {
        if (content.isNullOrEmpty()) {
            return
        }
        val dialog = CustomPopup(mActivity)
            .setLayoutId(R.layout.popup_welcome_back)
            .setControllerListener { dialog ->
                dialog.findViewById<TextView>(R.id.tvContent).text = content
            }.show()
        Handler().postDelayed(Runnable {
            dialog.dismiss()
        }, 3000)
    }

    /**
     * 卡片滑动监听
     */
    override fun onCardDragging(direction: Direction, ratio: Float) {
        isFlashChat = false
        if (direction == Direction.Left) {
            fragmentViewBinding?.imgViewIndexFragLike?.setImageResource(R.mipmap.ic_unselect_like)
            fragmentViewBinding?.imgViewIndexFragUnLike?.setImageResource(R.mipmap.icon_select_dislike)
        } else {
            fragmentViewBinding?.imgViewIndexFragLike?.setImageResource(R.mipmap.ic_select_like)
            fragmentViewBinding?.imgViewIndexFragUnLike?.setImageResource(R.mipmap.icon_unselect_dislike)
        }

    }

    val scope = MainScope()

    /**
     * 卡片滑动完成监听
     */
    override fun onCardSwiped(direction: Direction) {
        if (!turnOns && (manager.topPosition - 1 == turnOnsLimit)) {
            if (direction.toString() == "Right") {
                if (!isFlashChat) {
                    TOListPopup.openDialog(mActivity).setOnClickSaveListener(object :
                        TOListPopup.OnClickSaveListener {
                        override fun clickSave(dataList: ArrayList<TOListBean>) {
                        }

                    })
                }
                isFlashChat = false
            }
        } else {
            if (!isFlashChat) {
                if (direction.toString() == "Right") {
                    scope.launch {
                        var remainingWlmNum =
                            BaseConfig.getInstance.getInt(SpName.remainingWlmNum, 0) - 1
                        BaseConfig.getInstance.setInt(
                            SpName.remainingWlmNum,
                            remainingWlmNum
                        )

                    }
                }
                if (direction.toString() == "Right") {
                    if (continuousPassNum == 5 && PermissionUtils.lacksPermission(
                            mActivity,
                            Manifest.permission.ACCESS_FINE_LOCATION
                        ) && PermissionUtils.lacksPermission(
                            mActivity,
                            Manifest.permission.ACCESS_COARSE_LOCATION
                        )
                    ) {
                        PermissionUtils.requestPermission(mActivity, {}, {
                            val intent =
                                Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                            val uri = Uri.fromParts("package", mActivity.packageName, null)
                            intent.data = uri
                            mActivity.startActivityForResult(intent, 10008)
                        },
                            Manifest.permission.ACCESS_FINE_LOCATION,
                            Manifest.permission.ACCESS_COARSE_LOCATION
                        )
                        continuousPassNum = 0
                        adapter.setContinuousPassNum(continuousPassNum, manager.topPosition)
                        return
                    }
                    continuousPassNum = 0
                    adapter.setContinuousPassNum(continuousPassNum, manager.topPosition)
                } else {
                    if (continuousPassNum == locationLimit && PermissionUtils.lacksPermission(
                            mActivity,
                            Manifest.permission.ACCESS_FINE_LOCATION
                        ) && PermissionUtils.lacksPermission(
                            mActivity,
                            Manifest.permission.ACCESS_COARSE_LOCATION
                        )
                    ) {
                        continuousPassNum = 0
                        adapter.setContinuousPassNum(continuousPassNum, manager.topPosition)
                    } else {
                        if (!(manager.topPosition - 1 == 0 && !newUserFlag && PermissionUtils.lacksPermission(
                                mActivity,
                                Manifest.permission.ACCESS_FINE_LOCATION
                            ) && PermissionUtils.lacksPermission(
                                mActivity,
                                Manifest.permission.ACCESS_COARSE_LOCATION
                            ) && direction.toString() == "Left" && !BaseConfig.getInstance.getBoolean(
                                SpName.todayFirstRequestLocation + DateUtils.getTime(Date()),
                                false
                            ))
                        ) {
                            continuousPassNum++
                            adapter.setContinuousPassNum(continuousPassNum, manager.topPosition)
                        }
                    }
                }

                OkHttpManager.instance.requestInterface(object : OkHttpFromBoy {
                    override fun addBody(requestBody: OkHttpBodyEntity) {
                        requestBody.setPost(Constant.user_add_wlm_url)
                        requestBody.add(
                            "likeType",
                            if (direction.toString() == "Right") 1 else 4
                        )
                        requestBody.add(
                            "userCodeFriend",
                            adapter.getSpots()[manager.topPosition - 1].friendUserCode
                        )
                    }
                }, object : SDOkHttpResoutCallBack<MatchResultEntity>() {
                    override fun onSuccess(entity: MatchResultEntity) {
                        FirebaseEventUtils.logEvent(if (direction.toString() == "Right") FirebaseEventTag.Home_Like.name else FirebaseEventTag.Home_Pass.name)

                        if (direction.toString() == "Right" && entity.data.matched) {
                            val bundle = Bundle()
                            bundle.putString(
                                "userCode",
                                adapter.getSpots()[manager.topPosition - 1].userCode
                            )
                            bundle.putString(
                                "userCodeFriend",
                                adapter.getSpots()[manager.topPosition - 1].friendUserCode
                            )
                            bundle.putString(
                                "avatarUrl",
                                adapter.getSpots()[manager.topPosition - 1].avatarUrl
                            )
                            IntentUtil.startActivity(MatchedActivity::class.java, bundle)
                        }

                        if (manager.topPosition == adapter.getSpots().size) {
                            fragmentViewBinding?.conIndexFragUserList?.visibility = View.GONE
                        }
                    }

                    override fun onFailure(code: Int, msg: String) {
                        if (code == 3002) {
                            memberBuyShow(null, mActivity)
                        }
                        fragmentViewBinding?.cardViewIndexFrag?.rewind()
                    }
                })
            } else {
                if (direction.toString() == "Right") {
                    if (continuousPassNum == locationLimit && PermissionUtils.lacksPermission(
                            mActivity,
                            Manifest.permission.ACCESS_FINE_LOCATION
                        ) && PermissionUtils.lacksPermission(
                            mActivity,
                            Manifest.permission.ACCESS_COARSE_LOCATION
                        )
                    ) {
                        PermissionUtils.requestPermission(mActivity, {
                        }, {
                            val intent =
                                Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                            val uri = Uri.fromParts("package", mActivity.packageName, null)
                            intent.data = uri
                            mActivity.startActivityForResult(intent, 10008)
                        },
                            Manifest.permission.ACCESS_FINE_LOCATION,
                            Manifest.permission.ACCESS_COARSE_LOCATION
                        )
                        continuousPassNum = 0
                        adapter.setContinuousPassNum(continuousPassNum, manager.topPosition)

                    }
                }
            }
        }

        Log.e("~~~", "onCardSwiped:${adapter.itemCount}  ${adapter.itemCount / 3} ")
        if (manager.topPosition == adapter.itemCount - 10) {
            paginate()
        }
    }

    /**
     * 卡片回滚监听
     */
    override fun onCardRewound() {
    }

    /**
     * 卡片取消滑动监听
     */
    override fun onCardCanceled() {
        fragmentViewBinding?.imgViewIndexFragUnLike?.setImageResource(R.mipmap.icon_unselect_dislike)
        fragmentViewBinding?.imgViewIndexFragLike?.setImageResource(R.mipmap.ic_unselect_like)
    }

    /**
     * 卡片出现监听
     */
    override fun onCardAppeared(view: View, position: Int) {
        fragmentViewBinding?.conIndexFragUserActionContainer?.visibility =
            if (!turnOns && manager.topPosition == turnOnsLimit)
                View.GONE
            else if (continuousPassNum == locationLimit && PermissionUtils.lacksPermission(
                    mActivity,
                    Manifest.permission.ACCESS_FINE_LOCATION
                ) && PermissionUtils.lacksPermission(
                    mActivity,
                    Manifest.permission.ACCESS_COARSE_LOCATION
                ) && locationLimit > 0
            )
                View.GONE
            else
                View.VISIBLE
    }

    /**
     * 卡片消失监听
     */
    override fun onCardDisappeared(view: View, position: Int, direction: Direction) {
        fragmentViewBinding?.imgViewIndexFragUnLike?.setImageResource(R.mipmap.icon_unselect_dislike)
        fragmentViewBinding?.imgViewIndexFragLike?.setImageResource(R.mipmap.ic_unselect_like)
        if (position + 1 == adapter.itemCount) {
            fragmentViewBinding?.conIndexFragUserList?.visibility = View.GONE
            fragmentViewBinding?.linearIndexFragNoMore?.visibility = View.VISIBLE
        }
        //卡片滑动时，走likeOrDisLikeAnimation逻辑，根据滑动的值显示，当卡片移除时，走下面的动画逻辑
        if (direction.name == "Left") {
            val sY = com.luck.picture.lib.utils.DensityUtil.getRealScreenWidth(this.context) / 2
            fragmentViewBinding?.frameIndexFragUnLike?.animate()
                ?.translationX(-sY * 1f - DensityUtil.dp2pxF(mActivity, 120f))
                ?.alpha(1f)?.setDuration(500)
                ?.setListener(object : Animator.AnimatorListener {
                    override fun onAnimationStart(animation: Animator) {}
                    override fun onAnimationEnd(animation: Animator) {
                        fragmentViewBinding?.frameIndexFragUnLike?.translationX = 0f
                        fragmentViewBinding?.frameIndexFragUnLike?.setPadding(0, 0, 0, 0)
                        fragmentViewBinding?.frameIndexFragUnLike?.alpha = 0f
                    }

                    override fun onAnimationCancel(animation: Animator) {
                    }

                    override fun onAnimationRepeat(animation: Animator) {}
                })?.start()
        } else {
            val sY = com.luck.picture.lib.utils.DensityUtil.getRealScreenWidth(this.context) / 2
            fragmentViewBinding?.frameIndexFragLike?.animate()
                ?.translationX(sY * 1f + DensityUtil.dp2pxF(mActivity, 120f))
                ?.alpha(1f)?.setDuration(500)
                ?.setListener(object : Animator.AnimatorListener {
                    override fun onAnimationStart(animation: Animator) {}
                    override fun onAnimationEnd(animation: Animator) {
                        fragmentViewBinding?.frameIndexFragLike?.translationX = 0f
                        fragmentViewBinding?.frameIndexFragLike?.setPadding(0, 0, 0, 0)
                        fragmentViewBinding?.frameIndexFragLike?.alpha = 0f
                    }

                    override fun onAnimationCancel(animation: Animator) {
                    }

                    override fun onAnimationRepeat(animation: Animator) {}
                })?.start()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (manager != null)
            manager.removeAllViews()
    }


    fun refreshItem(userCode: String, onlineStatus: Int) {
        adapter?.let {
            for (i in 0 until adapter.getSpots().size) {
                if (adapter.getSpots()[i].friendUserCode == userCode) {
                    if (adapter.getSpots()[i].online != onlineStatus) {
                        Log.e("~~~", "refreshItem: " + adapter.getSpots().size)
                        adapter.getSpots()[i].online = onlineStatus
                        adapter.notifyItemChanged(i)
                    }
                    break
                }
            }
        }

    }

    //CardStackAdapter需要用到这个组件
    fun getUserActionViewId():ConstraintLayout?{
        return fragmentViewBinding?.conIndexFragUserActionContainer
    }
}